package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.SpecParamDTO;
import com.leyou.common.dto.SpuDetailDTO;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SpecParamMapper;
import com.leyou.item.service.CategoryService;
import com.leyou.item.service.SpecParamService;
import com.leyou.item.service.SpuDetailService;
import com.leyou.item.service.SpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


@Service
public class SpecParamServiceImpl extends ServiceImpl<SpecParamMapper, SpecParam> implements SpecParamService {

    @Autowired
    private SpuDetailService spuDetailService;

    @Autowired
    private SpuService spuService;

    @Autowired
    private SpecParamService specParamService;

    @Override
    public List<SpecParamDTO> queryParams(Long categoryId, Long groupId, Boolean searching) {
        // 健壮性判断
        if (categoryId == null && groupId == null) {
            // 条件不能都为空
            throw new LyException(400, "查询条件不能为空！");
        }
        // 查询
        List<SpecParam> list = query()
                .eq(categoryId != null, "category_id", categoryId)
                .eq(groupId != null, "group_id", groupId)
                .eq(searching != null, "searching", searching)
                .list();
        // 返回
        return SpecParamDTO.convertEntityList(list);
    }

    @Override
    public List<SpecParamDTO> querySpecParamBySpuId(Integer id, Boolean searching) {
        // 1.准备规格参数value
        // 1.1.根据id查询spuDetail
       // SpuDetail detail = spuDetailService.getById(id);
        List<SpuDetailDTO> spuDetailDTOS = spuDetailService.querSpuDeatilById(id);
        SpuDetail detail = spuDetailDTOS.get(0).toEntity(SpuDetail.class);
        // 1.2.获取其中的规格参数键值对，转为一个map
        Map<Long, Object> specValues = JsonUtils.toMap(detail.getSpecification(), Long.class, Object.class);

        // 2.准备规格参数对象
        // 2.1.根据id查询spu，获取商品分类信息
        Spu spu = spuService.getById(id);
        // 2.2.根据分类id查询规格参数集合，如果searching不为空，还要加上searching条件
        List<SpecParamDTO> params = specParamService.queryParams(spu.getCid3(), null, searching);

        // 3.找到param的value，并存储

        for (SpecParamDTO param : params) {
            param.setValue(specValues.get(param.getId()));
        }
        return params;
    }
}
